import React, { Component, Fragment } from 'react';
import Lottie from 'react-lottie';
import data from './data3.json';

import styles from './index.less';

class Demo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      speed: 1,
      direction: 1,
    };
  }

  componentDidMount() {
  }

  // 设置速度
  setSpeed = () => {
    const { speed } = this.state;
    this.setState({
      speed: speed + 1,
    }, () => {
      if (this.lottieRef) this.lottieRef.play();
    });
  };

  // 播放正反
  setDirection = () => {
    const { direction } = this.state;
    this.setState({
      direction: direction === 1 ? -1 : 1,
    }, () => {
      if (this.lottieRef) this.lottieRef.play();
    });
  };

  render() {
    const { speed, direction } = this.state;
    const options = {
      loop: true,
      autoplay: true,
      animationData: data,
      renderer: 'canvas',
    };

    const listener = [
      {
        eventName: 'complete',
        callback: () => {
          console.log('complete');
        },
      },
      {
        eventName: 'loopComplete',
        callback: () => {
          console.log('loopComplete');
        },
      },
      {
        eventName: 'enterFrame',
        callback: () => {
          // console.log('enterFrame');
        },
      },
      {
        eventName: 'loaded_images',
        callback: () => {
          console.log('loaded_images');
        },
      },
    ];
    return (
      <Fragment>
        <Lottie
          ref={(ref) => { if (ref) this.lottieRef = ref; }}
          options={options}
          eventListeners={listener}
          height={400}
          speed={speed}
          isPaused={true}
          direction={direction}
        />
        <button type="button" onClick={() => { if (this.lottieRef) this.lottieRef.stop(); }}>停止</button>
        <button style={{ marginLeft: '20px' }} type="button" onClick={() => { if (this.lottieRef) this.lottieRef.play(); }}>播放</button>
        <button style={{ marginLeft: '20px' }} type="button" onClick={() => { if (this.lottieRef) this.lottieRef.pause(); }}>暂停</button>
        <button style={{ marginLeft: '20px' }} type="button" onClick={this.setSpeed}>设置速度{speed}</button>
        <button style={{ marginLeft: '20px' }} type="button" onClick={this.setDirection}>播放正/反</button>
      </Fragment>
    );
  }
}

export default Demo;
